/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-18
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.sys.core.spring;

import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.RequestMatcher;

import com.hnas.sys.core.util.CacheUtil;

/**
 * @author 郑兴(zhengxing)
 *
 */
public class DTFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	private final static Logger log = LoggerFactory.getLogger(DTFilterInvocationSecurityMetadataSource.class);
	
	private final Map<RequestMatcher, Collection<ConfigAttribute>> requestMap;
	
	public DTFilterInvocationSecurityMetadataSource(MetaData metaData) {
       this.requestMap = metaData.getRequestMap();
    }

	//~ Methods ========================================================================================================
	
	/*
	 * (non-Javadoc)
	 * @see org.springframework.security.access.SecurityMetadataSource#getAllConfigAttributes()
	 */
    public Collection<ConfigAttribute> getAllConfigAttributes() {
    	Map<RequestMatcher, Collection<ConfigAttribute>> tempMap = requestMap;
    	if(CacheUtil.getMetaData().size() > 0) {
    		tempMap = CacheUtil.getMetaData();
    	}
        Set<ConfigAttribute> allAttributes = new HashSet<ConfigAttribute>();

        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : tempMap.entrySet()) {
            allAttributes.addAll(entry.getValue());
        }

        return allAttributes;
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.security.access.SecurityMetadataSource#getAttributes(java.lang.Object)
     */
    public Collection<ConfigAttribute> getAttributes(Object object) {
    	Map<RequestMatcher, Collection<ConfigAttribute>> tempMap = requestMap;
    	if(CacheUtil.getMetaData().size() > 0) {
    		tempMap = CacheUtil.getMetaData();
    	}
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : tempMap.entrySet()) {
            if (entry.getKey().matches(request)) {
                return entry.getValue();
            }
        }
        return null;
    }

    /*
     * (non-Javadoc)
     * @see org.springframework.security.access.SecurityMetadataSource#supports(java.lang.Class)
     */
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
